import { Component, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { SettingsService } from '../service/settings';
import { MessageUtilsService } from '../../shared/services/message-utils.service';
import { Message } from 'primeng/api';
@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit {
  displayDialog: boolean;
  msgs: Message[] = [];

  feature: any = {};

  selectedFeature: any;

  newFeature: boolean;

  features: any[];

  cols: any[];

  constructor(private settingsService:SettingsService,
            private messageUtilsService:MessageUtilsService) { }

  ngOnInit() {

    this.cols = [
      { field: 'id', header: 'ID' },
      { field: 'name', header: 'Name' },
      { field: 'description', header: 'Description' }
    ];

    this.load();
  }

  load(){
    this.settingsService.getAll().subscribe(
      (res)=>{
        this.feature = null;
        this.features = res;
        this.displayDialog = false;
      }
    );
  }



  save() {
    if (this.newFeature)
      this.create();
    else
      this.update();
  }

  create(){
    this.settingsService.insert(this.feature).subscribe(
      (res)=>{
        
        this.load();
        this.messageUtilsService.showInfo(this.msgs, res['msg']);
      },
      (err)=>{
        console.log(err);
        this.messageUtilsService.showError(this.msgs, 'Operation Failed.');
      }
    );
  }

  update(){
    this.settingsService.update(this.feature).subscribe(
      (res)=>{
        this.messageUtilsService.showInfo(this.msgs, res['msg']);
        this.load();
      },
      (err)=>{
        console.log(err);
        this.messageUtilsService.showError(this.msgs, 'Operation Failed.');
      }
    );

  }

  delete() {
    this.settingsService.delete([this.feature.id]).subscribe(
      (res)=>{
        this.messageUtilsService.showInfo(this.msgs, res['msg']);
        this.load();
      },
      (err)=>{
        console.log(err);
        this.messageUtilsService.showError(this.msgs, 'Operation Failed.');
      }
    );
  }

  showDialogToAdd() {
    this.newFeature = true;
    this.feature = {};
    this.displayDialog = true;
  }

  onRowSelect(event) {
    this.newFeature = false;
    this.feature = _.cloneDeep(event.data);
    this.displayDialog = true;
  }


}
